package controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.alibaba.fastjson.JSON;

import beans.*;
import dao.TaskDao;
import engine.BIEngine0_1.TaskThread;
import dao.HistoryTaskDao;
import dao.ModelDao;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import utils.Time2Str;
import utils.UserLogUtil;

/**
 * Servlet implementation class TaskServlet
 */
public class TaskServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private static TaskDao taskDao;
    private static HistoryTaskDao history_taskDao = new HistoryTaskDao();
    private static String userId;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TaskServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     * response)
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doPost(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */

    /**
     * @param
     * @author 施静�
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        userId = (String) session.getAttribute("userId");
        JSONObject dataJson = JSONObject.fromObject(request.getParameter("data"));
        String operateType = request.getParameter("operateType");
//        System.out.println("=====operateType:"+operateType);
//        System.out.println("=====dataJson:"+dataJson.toString());
        taskDao = new TaskDao();
        String result = "";
        switch (operateType) {
            case "showAll":
                doShowAll(request, response);
                break;
            case "showTask":
                doShowTask(request, response, dataJson);
                break;
            case "deleteTask":
                doDeleteTask(request, response, dataJson);
                break;
            case "addTask":
                doAddTask(request, response, dataJson);
                break;
            case "showTaskById":
                doShowTaskById(request, response, dataJson);
                break;
            case "showHistoryTask":
                doShowHistoryTask(request, response, dataJson);
                break;
            case "getJsonByModelId":
                doGetJsonByModelId(request, response, dataJson);
                break;
            case "addTaskByJson":
                doAddTaskByJson(request, response);
                break;
            case "showByTaskHash":
                doShowByTaskHash(request, response);
                break;
            case "showTaskDay":
                doTaskCount(request, response);
                break;
            case "getAlltaskNum":
                doGetAlltaskNum(request, response);
                break;
        }
        response.getWriter().print(result);
    }

    private void doShowByTaskHash(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String taskHash = request.getParameter("taskHash");
        HttpSession session = request.getSession();
        int state = -1;
        TaskThread taskThread = RunningTask.TASKMAP.getTask(taskHash);
        HistoryTask task = history_taskDao.getHistoryTaskByTaskHash(taskHash);
        JSONObject result = new JSONObject();
        result.put("json", task.getJson());
        if (taskThread.isAlive()) {
            if (taskThread.runningTaskBean.isPause)
                state = 2;
            else
                state = 1;
        } else {
            if (taskThread.runningTaskBean.isStop)
                state = 3;
            else
                state = 4;
        }
        result.put("taskState", state);
        response.getWriter().print(result.toString());

    }

    private void doAddTaskByJson(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String introduction = request.getParameter("introduction");

    }

    private void doGetJsonByTaskId(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String taskId = request.getParameter("taskId");
        Task task = (Task) taskDao.getTaskById(taskId).get(0);
        JSONObject content = new JSONObject();
        content.put("json", JSONObject.fromObject(task));
        response.getWriter().print(content.toString());
    }

    private void doGetJsonByModelId(HttpServletRequest request, HttpServletResponse response, JSONObject dataJson)
            throws IOException {
        String modelId = request.getParameter("modelId");
        ModelDao modelDao = new ModelDao();
        Model model = (Model) modelDao.getModelByModelId(modelId).get(0);
        JSONObject content = new JSONObject();
        content.put("json", JSONObject.fromObject(model));
        response.getWriter().print(content.toString());
    }

    /**
     * By 刘东�
     *
     * @param request
     * @param response
     * @throws IOException
     */
    private void doShowAll(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Integer onePageCount = Integer.parseInt(request.getParameter("onePageCount"));
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        List<Object> tasks = taskDao.getTasks(onePageCount, currentPage);
        int pagenum = taskDao.getTaskPageNum(onePageCount);
        JSONObject result = new JSONObject();
        JSONObject content = new JSONObject();
        content.put("tasks", JSONArray.fromObject(tasks));
        content.put("pageNum", pagenum);
        result.put("result", content);
        response.getWriter().print(result.toString());
    }

    // 增加任务
    private void doAddTask(HttpServletRequest request, HttpServletResponse response, JSONObject datajson) throws IOException {
        int model_id = Integer.parseInt(request.getParameter("modelId"));
        String name = request.getParameter("name");

        String json = request.getParameter("json");
        // Boolean is_nesting =
        // Boolean.parseBoolean(request.getParameter("is_nesting"));
        String nest_json = request.getParameter("nestJson");
        String introduction = request.getParameter("introduction");
        Task t = new Task();
        t.setModel_id(model_id);
        t.setName(name);
        t.setCreate_person(userId);
        t.setJson(json);
        // t.setIs_nesting(is_nesting);
        t.setNest_json(nest_json);
        t.setIntroduction(introduction);
        List<Object> results = taskDao.addTask(t);
        JSONObject result = new JSONObject();
        if (results.size() > 0) {
            result.put("taskId", results.get(0));
            result.put("result", true);
        } else {
            result.put("result", false);

        }
        response.getWriter().print(result.toString());
        // 日志记录
        UserLogUtil.dbLog(LogEnum.task, LogEnum.add,
                userId,
                LogEnum.task.getValue()+"编号："+results.get(0)+"，名称："+name+"，"
                        +LogEnum.model.getValue()+"编号："+model_id);
    }

    // 显示任务（不通过id的）
    private void doShowTask(HttpServletRequest request, HttpServletResponse response, JSONObject dataJson) throws IOException {
        // String taskId = dataJson.getString("taskId");
        List<Object> task = taskDao.getTaskByTaskId();
        JSONObject result = new JSONObject();
        result.put("result", JSONArray.fromObject(task));
        response.getWriter().print(result.toString());
    }

    // 删除任务
    private void doDeleteTask(HttpServletRequest request, HttpServletResponse response, JSONObject dataJson)
            throws IOException {
        // String taskId = dataJson.getString("taskId");
        String taskId = request.getParameter("taskId");
        Boolean resultId = taskDao.deteleTaskByTaskId(taskId);
        JSONObject result = new JSONObject();
        result.put("result", JSONArray.fromObject(resultId));
        response.getWriter().print(result.toString());
        // 日志记录
        UserLogUtil.dbLog(LogEnum.task, LogEnum.delete,
                userId,
                LogEnum.task.getValue()+"编号："+taskId);
    }

    // 通过id查询显示任务
    private void doShowTaskById(HttpServletRequest request, HttpServletResponse response, JSONObject dataJson)
            throws IOException {
        String taskId = request.getParameter("taskId");
        List<Object> task = taskDao.getTaskById(taskId);
        com.alibaba.fastjson.JSONObject result = new com.alibaba.fastjson.JSONObject();
        result.put("result", com.alibaba.fastjson.JSONArray.parseArray(JSON.toJSONString(task)));
        response.getWriter().print(result.toJSONString());
    }

    /**
     * @param request
     * @param response
     * @param dataIson
     * @throws IOException
     * @author chenlongxin
     */
    private void doShowHistoryTask(HttpServletRequest request, HttpServletResponse response, JSONObject dataIson)
            throws IOException {
        Integer onePageCount = Integer.parseInt(request.getParameter("onePageCount"));
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        List<Object> history_tasks = history_taskDao.getHistory_Tasks(onePageCount, currentPage);
        int pagenum = history_taskDao.historyTaskPageNum(onePageCount);
        JSONObject result = new JSONObject();
        JSONObject content = new JSONObject();
        content.put("history_tasks", JSONArray.fromObject(history_tasks));
        content.put("pageNum", pagenum);
        result.put("result", content);
        response.getWriter().print(result.toString());
    }

    private void doTaskCount(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 统计近一周的任务
        JSONObject history_tasks_week = history_taskDao.getHistory_Tasks_Week();
        // 统计近一天的任务
        JSONObject history_tasks_day = history_taskDao.getHistory_Tasks_Day();
        // 统计近一小时的任务
        JSONObject history_tasks_hour = history_taskDao.getHistory_Tasks_Hour();
        JSONObject result = new JSONObject();
        JSONObject content = new JSONObject();
        content.put("history_tasks_week", history_tasks_week.toString());
        content.put("history_tasks_day", history_tasks_day.toString());
        content.put("history_tasks_hour", history_tasks_hour.toString());
        result.put("result", content);
        response.getWriter().print(result.toString());
    }
    //获取所有renwu数量
    private void doGetAlltaskNum(HttpServletRequest request, HttpServletResponse response) throws IOException {
        HttpSession session = request.getSession();
//		String algorithmName = algorithmDao.getAlgorithmDetail(algorithmId, userId).getName();
        JSONObject result = new JSONObject();
        int taskNum = taskDao.getTaskPageNum();
        result.put("result", taskNum);
        response.getWriter().print(result.toString());
    }
}
